
import { _axis } from './axis.js'
import { _screen } from '../store/index.js'
import { translateY } from '../math/index.js'
import { canvasFnMap } from './registShape.js'
import { _show } from '../common/index.js'
import { _layout } from '../common/layout.js'

let timer
export const _canvas = (options = {}, props = {}) => {
  let {
    width = 800,
    height = 600,
    shapes,
    axis,
    o,
    layout
  } = options

  let screen = _screen(width, height)
  height = screen.height
  width = screen.width
  if (!o) {
    o = screen.o
  }

  let canvas = document.createElement('canvas')
  let ctx = canvas.getContext("2d")
  canvas.width = width
  canvas.height = height

  timer && cancelAnimationFrame(timer)


  let _main = () => {
    let fn = (t) => {
      let {
        shape
      } = t
      if (shape === 'lsystemPlant' && (layout == null || layout === '0')) {
        // 植物lsystem的原点下移
        o = translateY(o, height / 2 - 100)
      }

      canvasFnMap[shape] && canvasFnMap[shape](ctx, {
        o,
        ...t
      }, {
        stroke: 'blue',
        fill: 'none',
        ...t.props,
        ...props
      })

    }

    if (_show(axis)) {
      _axis(ctx, axis)
    }

    _layout({ layout, width, height, o }, shapes, fn)

    // 旋转动画
    let rotateShapes = shapes.filter(t => t.motion && t.motion.type === 'rotate')
    if (rotateShapes.length) {
      timer = requestAnimationFrame(() => {
        ctx.fillStyle = 'rgba(0,0,0,0.02)'
        ctx.fillRect(0, 0, width, height)
        rotateShapes.forEach(t => {
          let speed = t.motion.speed || 1
          t.a += speed
        })
        _main()
      })
    }

    // let rerenderShapes = shapes.filter(t => t.motion && t.motion.type === 'rerender')
    // if (rerenderShapes.length) {
    //   timer = requestAnimationFrame(() => {
    //     ctx.fillStyle = 'rgba(0,0,0,0.02)'
    //     ctx.fillRect(0, 0, width, height)
    //     _main()
    //   })
    // }

  }

  _main()

  return canvas
}